using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using RikMigrations.Providers;

namespace RikMigrations.Tests
{
	[TestFixture]
	public class MssqlProviderTests : DbProviderTests
	{
		MssqlProvider msDb;

		public MssqlProviderTests()
			: base(new MssqlProvider())
		{
			msDb = (MssqlProvider)db;
		}

		protected override void CreateSetupTestTable()
		{
			db.ExecuteNonQuery("CREATE TABLE SetupTestTable (" + SetupTestColumnName + " int)");
		    db.ExecuteNonQuery("CREATE View SetupTestView as select 1 as number");
		}

		[SetUp]
		public override void Setup()
		{
			db.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
			base.Setup();
		}

		[Test]
		public void PrimaryKey()
		{
			MssqlProvider msDb = new MssqlProvider();
			Table table = db.AddTable("Test");
			Column col = table.AddColumn("ID", typeof(int)).PrimaryKey();
			Assert.IsTrue(msDb.GetColumnSql(col).StartsWith("[ID] int"));
			Assert.IsTrue(msDb.GetColumnSql(col).Contains("PRIMARY KEY"));
		}

		[Test]
		public void CustomSqlType()
		{
			Table t = db.AddTable("TestTable");
			Column col = t.AddColumn("ID", null);
			col.SqlType = "faketype";
			Assert.IsTrue(msDb.GetColumnSql(col).StartsWith("[ID] faketype"));
		}
		
		[Test]
		public void FindForeignKey()
		{
			Assert.IsFalse(db.ColumnExists(SetupTestTableName, "Test"));
			Table table = db.AlterTable(SetupTestTableName);
			table.AddColumn("Test", typeof(int)).PrimaryKey();
			table.Save();

			Table table2 = db.AddTable("TestTable");
			table2.AddColumn("Test", typeof(int)).References(SetupTestTableName, "Test");
			table2.Save();

			Assert.AreEqual(1, table2.ForeignKeys.Count);
			ForeignKey fk = table2.ForeignKeys[0];
			Assert.AreEqual(fk.Column, "Test");
			Assert.AreEqual(fk.ForeignTable, SetupTestTableName);
			Assert.AreEqual(fk.ForeignColumn, "Test");
		}
	}
}